//
//  XWHDateExtension.swift
//  XiaoweHealthy
//
//  Created by Riven on 2022/4/22.
//

import Foundation


extension Date {

    func standardString(withFormat format: String = "dd/MM/yyyy HH:mm") -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale.init(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }
    
}

extension Date {
    
    /// 本地格式化转换
    func localizedString(withFormat: String = "yyyyMMMd HH:mm", locale: Locale = Locale.current) -> String {
        let lFormat =  DateFormatter.dateFormat(fromTemplate: withFormat, options: 0, locale: locale) ?? withFormat
//        lFormat.locale = Locale.init(identifier: "en_US_POSIX")
        
        return string(withFormat: lFormat)
    }
    
    
    
    var hourBegin: Self {
        return beginning(of: .hour) ?? self
    }
    
    var hourEnd: Self {
        return end(of: .hour) ?? self
    }
    
    var dayBegin: Self {
        return beginning(of: .day) ?? self
    }
    
    var dayEnd: Self {
        return end(of: .day) ?? self
    }
    
    var weekBegin: Self {
//        return beginning(of: .weekOfMonth) ?? self
        var cd = Calendar.current
        cd.firstWeekday = 2
        return cd.date(from: cd.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) ?? self
    }
    
    var weekEnd: Self {
//        return end(of: .weekOfMonth) ?? self
        return weekBegin.adding(.day, value: 7).adding(.second, value: -1)
    }
    
    var monthBegin: Self {
        return beginning(of: .month) ?? self
    }
    
    var monthEnd: Self {
        return end(of: .month) ?? self
    }
    
    var yearBegin: Self {
        return beginning(of: .year) ?? self
    }
    
    var yearEnd: Self {
        return end(of: .year) ?? self
    }
    
}

